import { initData, initPost } from '/@/api/data'
import { ref, reactive, watch, computed } from "vue";
import { ElMessage } from 'element-plus'
export const crud = <cruds.crud>reactive({
  tag: 'default',
  // id字段名
  idField: 'id',
  // 标题
  title: '',
  // 请求数据的url
  url: '',
  // 表格数据
  data: [],
  type: 'get',
  loading: false,
  // 选择项
  selections: [],
  // 待查询的对象
  query: {},
  // 查询数据的参数
  params: {},
  // Form 表单
  form: {},
  page: {
    // 页码
    page: 1,
    // 每页数据条数
    limit: 10,
    // 总数据条数
    total: 0
  },

  crudMethod: {
    add: (form) => { },
    del: (id) => { },
    edit: (form) => { },
    get: (id) => { }
  },
  // 重置表单
  defaultForm: () => { },

  selectionChangeHandler: (val) => {
    crud.selections = val
  },
  // 排序规则，默认 id 降序， 支持多字段排序 ['id,desc', 'createTime,asc']
  sort: ['id,desc'],
  // 等待时间
  time: 50,
  formtitle: "",//对话框标题
  // CRUD Method
  // 主页操作栏显示哪些按钮
  optShow: {
    add: true,
    edit: true,
    del: true,
    download: true,
    reset: true
  },
  // 自定义一些扩展属性
  props: {},

  dialogFormVisible: false,
  formLabelWidth: '80px',
  // 在主页准备
  queryOnPresenterCreated: true,
  // 调试开关
  debug: false,
  toQuery: () => {

    refresh()
  },
  sizeChangeHandler: (e) => {
    crud.page.limit = e
    crud.page.page = 1
    refresh()
    // refresh()
  },
  pageChangeHandler: (e) => {

    crud.page.page = e
    refresh()
  },
  toAdd: () => {
    crud.form = {}
    crud.formtitle = "新增" + crud.title
    crud.dialogFormVisible = true
    console.log(crud.dialogFormVisible);
    // console.log(crud)
  },
  toEdit: (data) => {
    crud.formtitle = "编辑" + crud.title
    crud.form = data

    crud.dialogFormVisible = true
    // console.log(crud);
    // console.log(crud)
  },
  submitCU: () => {
    crud.dialogFormVisible = false
    if (crud.formtitle == "编辑" + crud.title) {
      crud.crudMethod.edit(crud.form).then(() => {
        ElMessage.success('修改成功');
        refresh();
      }).catch(() => {

      })

    } else {
      crud.crudMethod.add(crud.form).then(() => {
        ElMessage.success('新增成功');
        refresh();

      }).catch(() => {

      })

    }


  }
})

export function toDelete(selections) {
  console.log(getids(selections))
  onDelete(getids(selections))

}
export function onDelete(data) {
  crud.crudMethod.del(data).then((res) => {
    ElMessage.success(res.message);
    refresh();

  }).catch(() => {

  })

}
function getids(selections) {
  return selections.map(res => {
    return res.id
  })
}
function refresh() {

  if (crud.type == 'post') {
    crud.loading = true


    initPost(crud.url, getQuerydata()).then(data => {
      crud.data = data.data.list
      crud.page.total = data.data.pagination.total

      crud.loading = false
    }).catch(err => {
      crud.loading = false
    })
  }
  else if (crud.type == 'get') {
    crud.loading = true
    initData(crud.url, getQueryParams()).then(data => {
      crud.data = data.data.list
      crud.page.total = data.data.pagination.total
      crud.loading = false
    }).catch(err => {
      crud.loading = false
    })
  }



}

export function pagination() {
  // return {
  //   data() {
  //     return {
  //       crud: this.crud,
  //       page: this.crud.page
  //     }
  //   },
  //   beforeCreate() {
  //     this.crud = lookupCrud(this)
  //     this.crud.registerVM('pagination', this, 2)
  //   },
  //   destroyed() {
  //     this.crud.unregisterVM('pagination', this)
  //   }
  // }
}

function getQueryParams() {
  // 清除参数无值的情况
  Object.keys(crud.query).length !== 0 && Object.keys(crud.query).forEach(item => {
    if (crud.query[item] === null || crud.query[item] === '') crud.query[item] = undefined
  })
  Object.keys(crud.params).length !== 0 && Object.keys(crud.params).forEach(item => {
    if (crud.params[item] === null || crud.params[item] === '') crud.params[item] = undefined
  })

  return {
    page: crud.page.page,
    limit: crud.page.limit,

    // sort: crud.sort,
    ...crud.query,
    ...crud.params
  }
}

function getQuerydata() {
  // 清除参数无值的情况
  Object.keys(crud.query).length !== 0 && Object.keys(crud.query).forEach(item => {
    if (crud.query[item] === null || crud.query[item] === '') crud.query[item] = undefined
  })
  Object.keys(crud.params).length !== 0 && Object.keys(crud.params).forEach(item => {
    if (crud.params[item] === null || crud.params[item] === '') crud.params[item] = undefined
  })

  return {
    page: crud.page.page,
    limit: crud.page.limit,

    // sort: crud.sort,
    ...crud.query,
    ...crud.params
  }
}
function before(options: any) {
  crud.title = options.title
  crud.url = options.url
  crud.type = options.type
  crud.crudMethod = options.crudMethod
  if (options.type == 'get') {
    crud.loading = true
    initData(options.url, getQueryParams()).then(data => {
      crud.data = data.data.list
      crud.page.total = data.data.pagination.total
      crud.loading = false
    }).catch(err => {
      crud.loading = false
    })
  } else if (options.type == 'post') {
    crud.loading = true
    initPost(options.url, getQuerydata()).then(data => {
      crud.data = data.data.list

      crud.page.total = data.data.pagination.total

      crud.loading = false
    }).catch(err => {
      crud.loading = false
    })
  }

}

// export function test() {
//   console.log(crud, 11111)
// }

export function CRUD(options) {
  before(options)
  // return
}

